package dao

import (
	"common"
	"context"
	"epai/internal/model"
	"errors"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

// AddPaozi 增加一个paozi商店扩展
func AddPaozi(ctx context.Context, db *gorm.DB, data map[string][]string, ind int) (*model.ShopExtPaozi, error) {
	paozi0, paozi := &model.ShopExtPaozi{}, &model.ShopExtPaozi{}

	// 处理具体信息
	uuidV := common.GenerateXID()
	shopId := data["shopID"][ind]
	sex := func() int {
		if strings.Contains(data["性别"][ind], "男") {
			return 1
		}
		return 2
	}()
	height, _ := strconv.ParseFloat(data["身高"][ind][:len(data["身高"][ind])-2], 64)
	weight, _ := strconv.ParseFloat(data["体重"][ind][:len(data["体重"][ind])-2], 64)
	chestCircumference := data["胸围"][ind]
	waistCircumference, _ := strconv.Atoi(data["腰围"][ind])
	hipCircumferencem, _ := strconv.Atoi(data["臀围"][ind])
	shoeSize, _ := strconv.Atoi(data["鞋码"][ind])
	xiaoHongShuFans, _ := strconv.Atoi(data["小红书粉丝"][ind])
	douYinFans, _ := strconv.Atoi(data["抖音粉丝"][ind])
	kuaiShouFans, _ := strconv.Atoi(data["快手粉丝"][ind])
	bZhanFans, _ := strconv.Atoi(data["B站粉丝"][ind])
	weiBoFans, _ := strconv.Atoi(data["微博粉丝"][ind])
	paozi = &model.ShopExtPaozi{
		ShopExtPaoziId:     uuidV,
		ShopId:             shopId,
		Sex:                sex,
		Height:             height,
		Weight:             weight,
		ChestCircumference: chestCircumference,
		WaistCircumference: waistCircumference,
		HipCircumference:   hipCircumferencem,
		ShoeSize:           shoeSize,
		XiaoHongShuFans:    xiaoHongShuFans,
		DouYinFans:         douYinFans,
		KuaiShouFans:       kuaiShouFans,
		BZhanFans:          bZhanFans,
		WeiBoFans:          weiBoFans,
	}

	// 查询是否存在
	if err := db.WithContext(ctx).Model(&model.ShopExtPaozi{}).Where(model.ShopExtPaozi{ShopId: shopId}).First(&paozi0).Error; err != nil {
		// 如果不存在则创建
		if errors.Is(err, gorm.ErrRecordNotFound) {
			paozi.ShopExtPaoziId = uuidV
			err := db.Create(&paozi).Error
			return paozi, err
		}
		return nil, err
	}

	// 存在，更新字段
	paozi.ShopExtPaoziId = paozi0.ShopExtPaoziId
	err := db.Model(&paozi).Where("shop_id = ?", shopId).Updates(paozi).Error
	return paozi, err
}

// GetPaozi 获取一个paozi商店扩展
func GetPaozi(ctx context.Context, db *gorm.DB, shopId string) (*model.ShopExtPaozi, error) {
	shopExtPaozi := &model.ShopExtPaozi{}
	err := db.WithContext(ctx).Model(&model.ShopExtPaozi{}).Where("shop_id = ?", shopId).First(&shopExtPaozi).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return shopExtPaozi, nil
	}
	return shopExtPaozi, err
}
